import { Behavior } from "./behavior"
import { RouteBehavior } from "./behavior-type"

export function setupRouteMonitor(behavior: Behavior): void {
    let lastPath = getPurePath(window.location.href)
    // 判断是否是hash路由
    const isHashMode = window.location.href.includes("#")

    // 重写history.pushState/replaceState
    // ===== 1. 监听 History 模式 =====
    const wrapHistoryMethod = (method: "pushState" | "replaceState") => {
        const original = window.history[method]
        window.history[method] = function (...args) {
            const url = args.length > 2 ? args[2] : undefined
            if (url && typeof url === "string") {
                handleRouteChange("history", lastPath, url, behavior)
                lastPath = getPurePath(url)
            }
            return original.apply(this, args)
        }
    }

    // ===== 2. 监听 Hash 模式 =====
    const handleHashChange = () => {
        const newPath = getPurePath(window.location.href)
        if (newPath !== lastPath) {
            handleRouteChange("hash", lastPath, newPath, behavior)
            lastPath = newPath
        }
    }

    // ===== 初始化监听 =====
    if (isHashMode) {
        // Hash 模式：监听 hashchange
        window.addEventListener("hashchange", handleHashChange)
    } else {
        // History 模式：重写 pushState/replaceState + 监听 popstate
        wrapHistoryMethod("pushState")
        wrapHistoryMethod("replaceState")
        window.addEventListener("popstate", () => {
            const newPath = getPurePath(window.location.href)
            handleRouteChange("history", lastPath, newPath, behavior)
            lastPath = newPath
        })
    }
}

// 统一处理路有变化
function handleRouteChange(type: string, from: string, to: string, behavior: Behavior): void {
    const routeData: RouteBehavior = {
        category: "Route",
        type,
        status: "ok",
        from: getPurePath(from),
        to: getPurePath(to),
        time: Date.now()
    }

    behavior.push(routeData)
}

// ===== 核心：从 URL 中提取纯路径（移除域名） =====
function getPurePath(fullUrl: string): string {
    try {
        const url = new URL(fullUrl)
        // Hash 模式：返回 # 及其后的部分（如 #/about）
        if (url.hash && url.hash !== "#") {
            return url.hash
        }
        // History 模式：返回路径部分（如 /home）
        return url.pathname + url.search
    } catch (e) {
        // 兼容非法 URL 或相对路径（如直接输入 '/home'）
        if (fullUrl.startsWith("#")) {
            return fullUrl // 已经是 Hash 路径
        }
        // 简单提取路径（适用于非完整 URL）
        const match = fullUrl.match(/^[^#]*/)
        return match ? match[0] : "/"
    }
}
